package ink.xiaobaibai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.bo.RequestEncryptionDataBo;
import ink.xiaobaibai.bo.UserInfo;
import ink.xiaobaibai.common.MySecurity;
import ink.xiaobaibai.entity.AdminUser;
import ink.xiaobaibai.entity.ClientUser;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IClientUserService;
import ink.xiaobaibai.service.ICouponService;
import ink.xiaobaibai.utils.TokenUtil;
import ink.xiaobaibai.utils.WxLoginHttp;
import ink.xiaobaibai.utils.WxUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @description: 用户接口
 * @author: 小白白
 * @create: 2021-05-19
 **/

@RestController
@Api(tags = "用户接口")
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private IClientUserService clientUserService;

    @Autowired
    private ICouponService couponService;

    @Autowired
    private IAdminUserService adminUserService;

    @PostMapping("/login")
    @ApiOperation("小程序用户登录|只需传入code")
    public ResponseFormat wxLogin(@RequestBody String code,
                                  HttpServletResponse response) {
        String[] strings = WxLoginHttp.obtainOpenid(code);
        if (strings == null) {
            return ResponseFormat.fail("code错误");
        }

        String openid = strings[0];
        String sessionKey = strings[1];

        QueryWrapper<ClientUser> q1 = new QueryWrapper<>();
        q1.select("id", "user_nickname", "user_image");
        q1.eq("user_openid", openid);
        ClientUser one = this.clientUserService.getOne(q1);

        String jwt;
        //首次登录,那么就博爱村当前用户信息
        if (one == null) {
            //默认昵称 默认头像
            ClientUser clientUser = new ClientUser("金牌用户", "http://image.xiaobaibai.ink/oxyimage.jpg", openid, sessionKey);
            //保存当前用户信息
            this.clientUserService.save(clientUser);
            jwt = TokenUtil.getJWT(clientUser.getId());
            clientUser.setUserOpenid(null);
            clientUser.setSessionKey(null);
            response.setHeader("Authorization", jwt);
            return ResponseFormat.ok("noInfo", clientUser);
        } else {
            //老用户
            jwt = TokenUtil.getJWT(one.getId());
            response.setHeader("Authorization", jwt);
            //更新一下sessionKey
            one.setSessionKey(sessionKey);
            this.clientUserService.updateById(one);
            one.setSessionKey(null);
            //是否已有个人信息
            return "金牌用户".equals(one.getUserNickname()) ? ResponseFormat.ok("noInfo", one) : ResponseFormat.ok("haveInfo", one);
        }

    }

    @GetMapping("/getUserInfo")
    @ApiOperation("获取用户昵称和头像和手机号")
    public ResponseFormat getUserInfo() {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<ClientUser> q1 = new QueryWrapper<>();
        q1.eq("id", userId);
        q1.select("user_nickname", "user_image", "user_phone");
        ClientUser clientUser = this.clientUserService.getOne(q1);
        return ResponseFormat.success(clientUser);
    }

    @PostMapping("/addUserInfo")
    @ApiOperation("添加用户昵称和头像")
    public ResponseFormat addUserInfo(@RequestBody @Validated UserInfo userInfo) {
        Integer userId = MySecurity.getUserId();
        ClientUser clientUser = this.clientUserService.getById(userId);
        clientUser.setUserImage(userInfo.getUserImage());
        clientUser.setUserNickname(userInfo.getUserNickname());
        this.clientUserService.updateById(clientUser);
        return ResponseFormat.success();
    }

    @PostMapping("/bindPhone")
    @ApiOperation("绑定电话|| iv和encryptedData")
    public ResponseFormat bindPhone(@RequestBody @Validated RequestEncryptionDataBo requestEncryptionDataBo) {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<ClientUser> q1 = new QueryWrapper<>();
        q1.select("session_key");
        q1.eq("id", userId);
        String sessionKey = this.clientUserService.getOne(q1).getSessionKey();
        String phone = WxUtil.decryptPhoneData(requestEncryptionDataBo.getIv(), requestEncryptionDataBo.getEncryptedData(), sessionKey);
        ClientUser clientUser = this.clientUserService.getById(userId);
        if (StringUtils.isBlank(clientUser.getUserPhone())) {
            //领取优惠券id为0的,绑定有理券 废弃,id为1的优惠券为空了
            this.couponService.receiveThisCouponById(1, MySecurity.getUserId());
        }
        clientUser.setUserPhone(phone);
        this.clientUserService.updateById(clientUser);
        return ResponseFormat.success(phone);
    }

    /**
     * 查询对应负责人信息
     */
    @GetMapping("/adminUser/{id}")
    @ApiOperation("查询对应负责人信息")
    public ResponseFormat getAdminUser(@PathVariable Integer id) {
        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.select("user_name", "user_phone");
        q1.eq("id", id);
        return ResponseFormat.success(this.adminUserService.getOne(q1));
    }

}
